﻿using System;
using System.IO;
using YioksPlanEditor.Yioks;

namespace YioksPlanEditor.Tools
{
    public class LogTool
    {
        public static void Log(string msg)
        {
            Log("", msg);
        }

        public static void Log(Exception msg)
        {
            Log("", msg);
        }


        public static void Log(string fileName, Exception ex)
        {
            Log(fileName, ex.ToString());
        }

        public static void Log(string fileName, string msg)
        {
            if (fileName == "")
            {
                if (YioksVar.SoftCfg.SoftDirectory != "")
                    fileName = YioksVar.SoftCfg.SoftDirectory + "/Log/" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
                else
                    fileName = AppDomain.CurrentDomain.BaseDirectory + "Log/" + DateTime.Now.ToString("yyyy_MM_dd") + ".log";
            }

            msg = "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + msg + "\r\n";
            File_SaveAdd(fileName, msg);
        }

        #region 将内容添加一个文件

        /// <summary>
        /// 将内容添加一个文件
        /// </summary>
        /// <param name="filePath">文件路经</param>
        /// <param name="content">文件内容</param>
        /// <returns>反回成功或失败</returns>
        private static void File_SaveAdd(string filePath, string content)
        {
            var path = @filePath;
            try
            {
                if (File.Exists(path))
                {
                    var sw = File.AppendText(path);
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                }
                else
                {
                    File_Save(filePath, content);
                }
            }
            catch (Exception ex)
            {

            }
        }
        #endregion


        #region 将内容保存成为一个文件
        /// <summary>
        /// 将内容保存成为一个文件
        /// </summary>
        /// <param name="filePath">文件路经</param>
        /// <param name="content">文件内容</param>
        /// <returns>反回成功或失败</returns>
        private static bool File_Save(string filePath, string content)
        {
            var path = @filePath;

            var dir = new DirectoryInfo(Path.GetDirectoryName(filePath));
            if (!dir.Exists)
                dir.Create();

            try
            {
                using (var sw = File.CreateText(path))
                {
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
        #endregion
    }
}
